﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CodeGenerator.interfaces;

namespace CodeGenerator.Implementations
{
    class ForeignKey : MultipleTargetObject, IForeignKey
    {
        private string _foreignTableName ="";
        private IList<IDataBaseColumnPair> _columns = new List<IDataBaseColumnPair>();
        private readonly IGeneratorModel _model;
        private readonly string _tableName;
        private string _foreignKeyName;
        private string _sourceCode = "";
        private string _indexName ="";

        public ForeignKey(IGeneratorModel Model, string TableName, string ForeignKeyName, IList<IDataBaseColumnPair> Columns, string ForeignTableName, string IndexName)
        {
            _model = Model;
            _tableName = TableName;
            _foreignKeyName = ForeignKeyName;
            _columns = Columns;
            _indexName = IndexName;
            if (_columns == null)
                _columns = new List<IDataBaseColumnPair>();
            _foreignTableName = ForeignTableName;
        }

        public string TableName
        {
            get { return _tableName; }
        }

        public string IndexName
        {
            get { return _indexName; }
        }

        public string ForeignTableName
        {
            get { return _foreignTableName; }
        }

        public string ForeignKeyName
        {
            get { return _foreignKeyName; }
        }

        public IGeneratorClass ForeingClass
        {
            get
            {
                var x = (from IGeneratorClass n in _model.Classes
                                    where n.DatabaseTable.TableName.ToUpper().Equals(this._foreignTableName.ToUpper())
                                    select n);
                if (x.Count() > 0)
                    return x.ToList()[0];
                return null;
            }
        }

        public IList<IDataBaseColumnPair> Columns
        {
            get { return _columns; }
        }

        public string LocalVariableName
        {
            get
            {
                string res = Common.Formatting.FormatPascalCase(ForeingClass.ClassName);
                res = "_" + res.Substring(0, 1).ToLower() + res.Substring(1);
                return res;
            }
        }

        public string SourceCode
        {
            get { return _sourceCode; }
            set { _sourceCode = value; }
        }
    }
}
